/**
 * @file lv_custom_focus.c
 * @brief 自定义 LVGL 焦点控制模块实现
 */

#include "lv_custom_focus.h"
#include "lv_port_indev.h"
#include "lvgl.h"
#include <stdlib.h>

/** 控件映射结构 */
typedef struct {
    lv_obj_t *obj;       /**< 当前控件 */
    lv_obj_t *up;        /**< 向上键对应的目标控件 */
    lv_obj_t *down;      /**< 向下键对应的目标控件 */
    lv_obj_t *left;      /**< 向左键对应的目标控件 */
    lv_obj_t *right;     /**< 向右键对应的目标控件 */
} ControlMapping;

/** 全局变量 */
static ControlMapping *control_mapping = NULL;
static uint8_t max_controls = 0;
static uint8_t control_count = 0;
static lv_group_t *current_group = NULL;

/**
 * 根据方向键和当前控件获取下一个控件
 * @param current 当前控件
 * @param key 按键码 (使用 LV_KEY_* 常量)
 * @return 下一个控件或 NULL
 */
static lv_obj_t* get_next_control(lv_obj_t *current, lv_key_t key) {
    if(!current || !control_mapping) return NULL;

    for(uint8_t i = 0; i < control_count; i++) {
        if(control_mapping[i].obj == current) {
            switch(key) {
                case LV_KEY_UP:    return control_mapping[i].up;
                case LV_KEY_DOWN:  return control_mapping[i].down;
                case LV_KEY_LEFT:  return control_mapping[i].left;
                case LV_KEY_RIGHT: return control_mapping[i].right;
                default:           return NULL;
            }
        }
    }

    return NULL;
}

extern lv_key_t current_nav_key;
/**
 * 自定义焦点回调函数
 * @param group 焦点组
 * @param key 按键码 (使用 LV_KEY_* 常量)
 */
static void custom_focus_cb(lv_group_t *group) {
    lv_obj_t *current = lv_group_get_focused(group);
    lv_obj_t *next = NULL;
    lv_key_t key = current_nav_key;

    if(!current) return;

    // 处理方向键
    next = get_next_control(current, key);

    LV_LOG_INFO("Next object: %p", next);

    if(next != NULL) {
        // 清除当前焦点样式
        // lv_obj_clear_state(current, LV_STATE_FOCUSED);

        // 设置新焦点
        lv_group_focus_obj(next);
        lv_obj_add_state(next, LV_STATE_FOCUSED);

        // 滚动到可见区域（可选）
        lv_obj_scroll_to_view(next, LV_ANIM_ON);
    }


}

/* 实现头文件中声明的函数 */
void 
lv_custom_focus_init(uint8_t max) {
    if(max == 0) return;

    // 释放之前的内存（如果有）
    if(control_mapping) {
        free(control_mapping);
        control_mapping = NULL;
    }

    // 分配新内存
    control_mapping = (ControlMapping*)malloc(max * sizeof(ControlMapping));
    if(!control_mapping) {
        max_controls = 0;
        return;
    }

    max_controls = max;
    control_count = 0;
}

void lv_custom_focus_add_control(lv_obj_t *obj, lv_obj_t *up, lv_obj_t *down, lv_obj_t *left, lv_obj_t *right) {
    if(!obj || !control_mapping || control_count >= max_controls) return;

    control_mapping[control_count] = (ControlMapping){
        .obj = obj,
        .up = up,
        .down = down,
        .left = left,
        .right = right
    };

    control_count++;
}

void lv_custom_focus_set_group(lv_group_t *group) {
    if(!group) return;

    current_group = group;
    lv_group_set_focus_cb(group, custom_focus_cb);
}

void lv_custom_focus_set_initial_focus(lv_obj_t *obj) {
    if(!obj || !current_group) return;

    lv_group_focus_obj(obj);
}


bool lv_custom_focus_keypad_read(lv_indev_drv_t * indev_drv, lv_indev_data_t * data)
{
    static uint32_t last_key = 0;
    static lv_indev_state_t last_state = LV_INDEV_STATE_REL;

    uint32_t cur_key = keypad_get_key();  // 你自己的按键读取函数

    if (cur_key != 0 && last_state == LV_INDEV_STATE_REL) {
        // 第一次按下
        data->state = LV_INDEV_STATE_PR;
        data->key = cur_key;
        last_key = cur_key;
        last_state = LV_INDEV_STATE_PR;

        // 如果是方向键，立即跳焦点
        if (cur_key == 1 || cur_key == 2 || cur_key == 4 || cur_key == 7) {
            current_nav_key = cur_key;
            if (current_group) {
                custom_focus_cb(current_group);
            }
        } else {
            current_nav_key = 0;
        }

        return false;
    }

    if (cur_key == 0 && last_state == LV_INDEV_STATE_PR) {
        // 按键释放
        data->state = LV_INDEV_STATE_REL;
        data->key = last_key;
        last_key = 0;
        last_state = LV_INDEV_STATE_REL;
        current_nav_key = 0;
        return false;
    }

    // 无变化
    data->state = LV_INDEV_STATE_REL;
    data->key = 0;
    return false;
}



// bool lv_custom_focus_keypad_read(lv_indev_drv_t *drv, lv_indev_data_t *data) {
//     static uint32_t last_key = 0;
//     uint32_t cur_key = keypad_get_key();  // 假设这是你的硬件按键读取函数

//     if (cur_key != 0) {
//         data->state = LV_INDEV_STATE_PR;  // 按键按下状态
//         last_key = cur_key;
//     } else {
//         data->state = LV_INDEV_STATE_REL;  // 按键释放状态
//         current_nav_key = 0;
//         // 处理返回键逻辑（键值6）
//         if(last_key == 6) {
//             handle_physical_back_button();  // 调用返回处理函数
//         }

//         last_key = cur_key;
//     }

//     // 根据硬件按键值映射到LVGL按键码
//     switch(last_key) {
//         case 1:  // 上
//             data->key = LV_KEY_UP;
//             break;

//         case 2:  // 右
//             data->key = LV_KEY_RIGHT;
//             break;

//         case 4:  // 下
//             data->key = LV_KEY_DOWN;
//             break;

//         case 7:  // 左
//             data->key = LV_KEY_LEFT;
//             break;

//         case 5:  // 确认/回车
//             data->key = LV_KEY_ENTER;
//             break;

//         case 6:  // 返回/ESC
//             data->key = LV_KEY_ESC;
//             break;

//         default:
//             data->key = 0;  // 无效按键
//             break;
//     }

//     return false;
// }
